import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/mine/mine_preview_page.dart';
import 'package:find_friend/pages/mine/model/followmodel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';



class MineFollowPage extends StatefulWidget {

  final bool notshowAppbar;
  _MineFollowPageState _state;
  MineFollowPage({Key key, this.notshowAppbar = false}) : super(key: key);

  void refreshData() {
    _state._onRefresh();
  }
  @override
  _MineFollowPageState createState() => _state = _MineFollowPageState();
}

class _MineFollowPageState extends State<MineFollowPage> {

  bool offstage = false;
  bool selectall = false;
  List<FollowModel> list = [];
  List<FollowModel> unFollow = [];
  int page = 0;
  RefreshController _refreshController = RefreshController(initialRefresh: true);

  @override
  void initState() {
    super.initState();

    _request();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  _onRefresh() {
    page = 1;
    _request(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _request();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 10) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _request({bool isrefresh = false}) {
    Networktool.request(API.follow, params: {"rows":10, "page":page}, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        if(data["data"]["data"] == null) return;
        MineFollowListModel model = MineFollowListModel.fromJson(data["data"]);
        _endNormoreData(model.data?.length ?? 0);
        if(isrefresh) list.clear();
        list.addAll(model.data);
        if(mounted) setState(() {});
      }
    }
    ,finaly: _endrefres
    );
  }

  _requestUnfollow() {
    if(unFollow.isEmpty) return;
    final mobiles = unFollow.map((e) => e.mobile).toList().join(',');
    Networktool.request(API.follow, params: {"mobiles": mobiles}, method: NETWORKHTTPMethod.DELETE, success: (data){
      list.forEach((element) { element.isfollow = false; });
      AlertTool.showToast("全部取关成功");
      // 更新UI
      setState(() {
        offstage = !offstage;
        unFollow.clear();
      });
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.notshowAppbar == true ? null : AppBar(
        title: Text("星域"),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [
              const Color(0xFFffe92e),
              const Color(0xFFfbd001),
            ], begin: Alignment(-1.5,0.5), end: Alignment(0, 0)),
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
        actions: [
          InkWell(
            onTap: () => Navigator.pushNamed(context, '/search'),
            child: Image.asset("assets/sousuo.png", width: 30,color: Colors.black,)
          ),
          InkWell(
            onTap: (){
              selectall = false;
              setState(() {
                offstage = !offstage;
              });
            },
            child: Image.asset("assets/bianji.png", width: 30,),
          )
        ],
      ),
      body: SafeArea(
        bottom: offstage,
        child: Column(
          children: [
            Expanded(
              child: CustomRefreshWidget(
                controller: _refreshController,
                onRefresh: _onRefresh,
                enablePulldown: !widget.notshowAppbar,
                onLoading: _onLoading,
                page: page,
                child: ListView.builder(
                  itemCount: list.length,
                  itemBuilder: (context, index){
                  return MineFollowCell(
                    offstage: offstage, 
                    isselect: unFollow.contains(list[index]),
                    model: list[index],
                    onSelectTap: (isselect){
                      setState(() {
                        if(isselect){
                          unFollow.add(list[index]);// 全部取关
                        } else {
                          unFollow.remove(list[index]);
                        }
                      });
                    },
                  );
                }),
              ),
            ),
            SelectAllfootWidget(
              isselect: selectall,
              offstage: !offstage,
              isenable: unFollow.length != 0,
              onUnfollowTap: _requestUnfollow,
              onTap: (){
                setState(() {
                  selectall = !selectall;
                  if(selectall){
                    unFollow.addAll(list);// 全部取关
                  } else {
                    unFollow.clear();
                  }
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

class SelectAllfootWidget extends StatelessWidget {

  final bool offstage;
  final bool isselect;
  final Function onTap;
  final Function onUnfollowTap;// 取关
  final bool isenable; //取关按钮是否可以点击
  final String submitBtnTitle;

  const SelectAllfootWidget({
    Key key, 
    this.offstage, 
    this.isselect, 
    this.onTap, 
    this.isenable = false,
    this.submitBtnTitle = "取关",
    this.onUnfollowTap
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Offstage(
              offstage: offstage,
              child: Container(
                padding: const EdgeInsets.fromLTRB(25, 15, 20, 15),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: onTap,
                      child: Row(
                        children: [
                          SelectIconWidget(isselect: isselect,),
                          SizedBox(width: 10.5),
                          Text("全选此页面",),
                        ],
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: onUnfollowTap,
                      child: Container(
                        padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 11.5),
                        decoration: BoxDecoration(
                          color: isenable ? APP_main_color : Colors.white,
                          borderRadius: BorderRadius.circular(5),
                          border: Border.all(color: APP_main_color, width: 0.5)
                        ),
                        alignment: Alignment.center,
                        child: Text(submitBtnTitle, style: instanceTextStyle(14, isenable ? Colors.white : APP_font_black),),
                      ),
                    )
                  ],
                ),
              ),
            );
  }
}

class MineFollowCell extends StatefulWidget {

  final bool offstage;
  bool isselect;
  final Function(bool isfollow) onSelectTap;
  final FollowModel model;

  MineFollowCell({
    Key key,
    this.offstage,
    this.isselect = false,
    this.onSelectTap,
    this.model
  }) : super(key: key);

  @override
  _MineFollowCellState createState() => _MineFollowCellState();
}

class _MineFollowCellState extends State<MineFollowCell> {

  bool isselected = false;

  @override
  void initState() {
    super.initState();

  }

   _request() {
    Networktool.request(API.follow, params: {widget.model.isfollow == true ? "mobiles" : "mobile": widget.model.mobile}, method: widget.model.isfollow ? NETWORKHTTPMethod.DELETE : NETWORKHTTPMethod.POST, success: (data){
      setState(() {
        widget.model.isfollow = !widget.model.isfollow;
      });
    },
    fail: (msg) => AlertTool.showToast(msg));
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Slidable(
        actionPane: SlidableDrawerActionPane(),
        actionExtentRatio: 0.18,// 按钮所占的宽度
        secondaryActions: [
          SlideAction(
            color: const Color(0xffdddddd),
            child: Text("取消置顶",style: instanceTextStyle(11, Colors.white),),
          ),
          SlideAction(
            onTap: _request,
            color: APP_main_color,
            child: Text(widget.model.isfollow ? "取消关注" : "关注", style: instanceTextStyle(11, Colors.white),),
          ),
        ],
        child: InkWell(
          onTap: (){
            setState(() {
              widget.isselect = !widget.isselect;
            });
            if(widget.onSelectTap != null) widget.onSelectTap(widget.isselect);
          },
          child: Container(
            padding: const EdgeInsets.only(left: 20, top: 10, right: 0),
            child: Column(
              children: [
                Row(
                  children: [
                    InkWell(
                      onTap: (){
                        push(context, MinePreviewPage(mobile: widget.model?.mobile));
                      },
                      child: CustomCircleAvatar(size: 46.h,url: widget.model?.avatar,)
                    ),
                    SizedBox(width: 10,),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(widget.model?.remarkname ?? "", style: instanceTextStyle(14, APP_font_black),),
                          Container(
                            child: Text(
                              "${widget.model?.bio ?? '--'}",
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: instanceTextStyle(10, APP_font_black),
                            ),
                          ),
                        ],
                      ),
                    ),
                    
                    widget.offstage ? SelectIconWidget(
                        margin: const EdgeInsets.only(right: 15),
                        isselect: widget.isselect,
                      ) : SizedBox(width: 21,)
                  ],
                ),
                SizedBox(height: 10,),
                Divider(height: 0.5, color: APP_divider_color, indent: 15, endIndent: 30,)
              ],
            ),
          ),
        ),
      ),
    );
  }
}